#!/bin/bash	

ACTION=$1	

case "${ACTION}" in	
	"unlock-volume")
		echo "obsolete"
	;;	

	"list")	
		echo "auto"	
		echo "custom"	
		LC_ALL=C aplay -l | grep -E '^card [0-9]*:' | sed -e s+'^card \([0-9]*\): \(.*\), device \([0-9]*\): [^\[]* \[\([^]]*\)].*$'+'\1,\3 \4 \2'+	
	;;	

	"get")	
		batocera-settings -command load -key audio.device	
	;;	

	"set")	
		MODE=$2	
		# auto: no .asoundrc
		# custom: don't touch .asoundrc	
		# any other, create .asoundrc
		if [ "${MODE}" == "auto" ];then	
			rm -f /userdata/system/.asoundrc
		elif [ "${MODE}" != "custom" ];then	
			if echo "${MODE}" | grep -qE '^[0-9]*,[0-9]* ';then	
				cardnb=$(echo "${MODE}" | sed -e s+'^\([0-9]*\),.*$'+'\1'+)	
				devicenb=$(echo "${MODE}" | sed -e s+'^[0-9]*,\([0-9]*\) .*$'+'\1'+)	
				cat > /userdata/system/.asoundrc <<EOF
pcm.!default { type plug slave { pcm "hw:${cardnb},${devicenb}" } }	
ctl.!default { type hw card ${cardnb} }	
EOF
			fi	
		fi
	;;

	"test")
		aplay "/usr/share/sounds/Mallet.wav"
	;;
esac